/*
 * This file is part of aion-engine <aion-engine.com>
 *
 * aion-engine is private software: you can redistribute it and or modify
 * it under the terms of the GNU Lesser Public License as published by
 * the Private Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * aion-engine is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser Public License for more details.
 *
 * You should have received a copy of the GNU Lesser Public License
 * along with aion-engine.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.aionengine.gameserver.controllers.observer;

import com.aionengine.gameserver.geoEngine.collision.CollisionResults;
import com.aionengine.gameserver.geoEngine.math.Ray;
import com.aionengine.gameserver.geoEngine.math.Vector3f;
import com.aionengine.gameserver.geoEngine.scene.Spatial;
import com.aionengine.gameserver.model.gameobjects.Creature;
import com.aionengine.gameserver.utils.ThreadPoolManager;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author MrPoke
 * @moved Rolandas
 */
public abstract class AbstractCollisionObserver extends ActionObserver {

    protected Creature creature;
    protected Vector3f oldPos;
    protected Spatial geometry;
    protected byte intentions;
    private AtomicBoolean isRunning = new AtomicBoolean();

    public AbstractCollisionObserver(Creature creature, Spatial geometry, byte intentions) {
        super(ObserverType.MOVE_OR_DIE);
        this.creature = creature;
        this.geometry = geometry;
        this.oldPos = new Vector3f(creature.getX(), creature.getY(), creature.getZ());
        this.intentions = intentions;
    }

    @Override
    public void moved() {
        if (!isRunning.getAndSet(true)) {
            ThreadPoolManager.getInstance().execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        Vector3f pos = new Vector3f(creature.getX(), creature.getY(), creature.getZ());
                        Vector3f dir = oldPos.clone();
                        Float limit = pos.distance(dir);
                        dir.subtractLocal(pos).normalizeLocal();
                        Ray r = new Ray(pos, dir);
                        r.setLimit(limit);
                        CollisionResults results = new CollisionResults(intentions, true, creature.getInstanceId());
                        geometry.collideWith(r, results);
                        onMoved(results);
                        oldPos = pos;
                    } finally {
                        isRunning.set(false);
                    }
                }
            });
        }
    }

    public abstract void onMoved(CollisionResults result);
}
